package org.itboys.fuzion.mysql.service;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.itboys.fuzion.dto.PublicRowDto;
import org.itboys.fuzion.entity.FuzionMember;
import org.itboys.fuzion.mysql.dao.PublicRowMapper;
import org.itboys.fuzion.mysql.orm.FuziongMemberStatistics;
import org.itboys.fuzion.mysql.orm.PublicRow;
import org.itboys.fuzion.mysql.orm.PublicRowRecord;
import org.itboys.fuzion.service.FuzionMemberService;
import org.itboys.mongodb.utils.page.PageQueryParam;
import org.itboys.mongodb.utils.query.AceUtils;
import org.itboys.mongodb.utils.query.PageQueryUtils;
import org.itboys.mongodb.utils.query.QueryParamUtils;
import org.itboys.redis.RedisCacheClient;
import org.mongodb.morphia.query.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;

import javax.servlet.http.HttpServletRequest;

/**
 * 公排逻辑
 * @author weisky
 *
 * 2016年4月22日
 */
@Service
public class PublicRowService {
	
	private static  Logger logger = LoggerFactory.getLogger(PublicRowService.class);
	
	@Autowired
	private PublicRowMapper publicRowMapper;
	@Autowired
	private PublicRowRecordService publicRowRecordService;
	@Autowired
	private RedisCacheClient redisCacheClient;
	@Autowired
	private FuziongMemberStatisticsService fuziongMemberStatisticsService;
	@Autowired
	private FuzionMemberService fuzionMemberService;
	
	private static final String FUZION_PUBLIC_ROW_KEY = "FUZION_PUBLIC_ROW_KEY";

	public void delete(Long id){
		publicRowMapper.delete(id);
    }

	//@Transactional
	public void insert(PublicRow record){
		publicRowMapper.insert(record);
    }

	public PublicRow getById(Long id){
    	return publicRowMapper.getById(id);
    }
	
	//@Transactional
	public void updatePushId(PublicRow record){
		publicRowMapper.updatePushId(record);
	}
	
    /**
     * 统计pushID个数
     * @return
     */
    public Map<String, Object> countNowInfo(){
    	return publicRowMapper.countNowInfo();
    }


	/**
     * 获取数据库中  最大的ID值
     * @return
     */
    public Long getMaxId(){
    	return publicRowMapper.getMaxId();
    }
    
    /**
	 * 公排逻辑
	 * @param memberId
	 */
	//@Transactional
	public void buyThanPublicRow(Long memberId){
		
		try{
			Long index = redisCacheClient.get(FUZION_PUBLIC_ROW_KEY, Long.class);
			if(index == null){//新的开始  或者redis缓存服务器重启
				index = getMaxId();
				if(index == null){
					index = 0L;
				}
				redisCacheClient.set(FUZION_PUBLIC_ROW_KEY, index, 0);//将数据库中 最后一条数据的ID值  放入缓存中
			}
			Long pushId = indexId(index + 1L);//计算弹出值
			
			PublicRow pr = new PublicRow();
			pr.setMemberId(memberId);
			pr.setPushId(pushId);
			insert(pr);
			
			//判断是否符合抽奖条件
			Map<String, Object> resut = countNowInfo();
			Long renum = (Long)resut.get("num");
			Long repushId = (Long)resut.get("pushId");
			if(renum >= 3){//如果满足抽奖条件  就从抽奖池中删除  表示已经抽过奖
				delete(repushId);
				
				PublicRowRecord prr = new PublicRowRecord();
				prr.setMemberId(pr.getMemberId());
				prr.setPushId(pr.getId());//这里的弹出ID  就是这条memberid的ID值
				publicRowRecordService.insert(prr);//插入一条记录
				
				//重新计算已玩局数 静态收益(开奖部分)
				reStatistics(memberId);
			}
			
			redisCacheClient.set(FUZION_PUBLIC_ROW_KEY, pr.getId(), 0);//重新设定缓存中的值
		}catch(Exception e){
			e.printStackTrace();
			logger.error("PublicRowService.buyThanPublicRow error", e);
		}
	}
	
    /**
     * 统计奖金池中的会员数量
     * @return
     */
    public int getNumByMemberId(List<Long> memberIdList){
    	return publicRowMapper.getNumByMemberId(memberIdList);
    }
	
	/**
	 * 重新计算已玩局数 静态收益(开奖部分)
	 * @param memberId
	 */
	//@Transactional
	private void reStatistics(Long memberId){
		try{
			FuziongMemberStatistics fms = fuziongMemberStatisticsService.getByMember(memberId);
			fms.setPlayNum(fms.getPlayNum() + 1);//已玩局数+1
			fms.setNowEnergyBean(fms.getNowEnergyBean() + 1);//现在持有的能量豆数量+1
			fms.setEnergyBean(fms.getEnergyBean() + 1);//历史拥有的能量豆数量+1
			fms.setTotalMoney(fms.getTotalMoney() + 20200);//因为开奖  历史总金额+202块钱 
			fms.setNowTotalMoney(fms.getNowTotalMoney() + 20200);//因为开奖  可提现金额+202块钱
			fms.setStaticIncome(fms.getStaticIncome() + 20200);//因为开奖  静态收益+202块钱
			fuziongMemberStatisticsService.updateByMemberId(fms);
			
			logger.info("开奖后，重新计算已玩局数、静态收益成功：FuziongMemberStatistics="+JSON.toJSONString(fms));
		}catch(Exception e){
			e.printStackTrace();
			logger.error("PublicRowService.reStatistics error", e);
		}
	}
	
	/**
	 * 通过id 计算弹出的ID
	 * @param id
	 * @return
	 */
	private Long indexId(Long id){
		return Math.round(Math.ceil((id+1l)/3l));
	}
	
    /**
     * 获取公排池中  所有待排位的值
     * @return
     */
    public List<PublicRowDto> getPublicRowPoolAll(Map<String, Object> param){
    	//fuzionMemberService
    	List<PublicRow> list = publicRowMapper.getPublicRowPoolAll(param);
    	List<PublicRowDto> resList = Lists.newArrayListWithExpectedSize(list.size());
    	if(list != null){
    		list.forEach(ll->{
    			PublicRowDto pr = new PublicRowDto();
    			pr.setId(ll.getId());
    			pr.setMemberId(ll.getMemberId());
    			pr.setPushId(ll.getPushId());
    			pr.setScoreId(ll.getId());
    			pr.setCreateTime(ll.getCreateTime());
    			FuzionMember fm = fuzionMemberService.getById(ll.getMemberId());
    			if(fm != null){
    				pr.setMemberName(fm.getNickname());
					pr.setHeadImg(fm.getLogo());
    			}
    			resList.add(pr);
    		});
    	}
    	return resList;
    }

	public long count(Map<String,Object> paramMap){
		return publicRowMapper.count(paramMap);
	}

	/**
	 * 根据pushId 统计总数
	 * @param pushId
	 * @return
     */
	public Long countPushId(Long pushId){
		return pushId;
	}
}





































